package csu.web.mypetstore.controller;

import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping("user/{username}/cart")
    public Result getCart(@PathVariable("username") String username){
        return cartService.getCart(username);
    }
    @DeleteMapping("user/{username}/cart")
    public Result clearCart(@PathVariable("username") String username){
        return cartService.clearCart(username);
    }
    @PostMapping("user/{username}/cart/{itemId}")
    public Result addToCart(@PathVariable("username") String username, @PathVariable("itemId") String itemId,@RequestParam("quantity") int quantity){
       //System.out.println("username: "+username+" itemId: "+itemId+" quantity: "+quantity);
      return  cartService.addToCart(username, itemId, quantity);
    }
    @DeleteMapping("user/{username}/cart/{itemId}")
    public Result removeCartItem(@PathVariable("username") String username, @PathVariable("itemId") String itemId) {
        cartService.deleteItem(itemId, username);
        return Result.success("删除 "+itemId+" 成功");
    }
    @PutMapping("user/{username}/cart/{itemId}")
    public Result updateCartItemQuantity(@PathVariable("username") String username, @PathVariable("itemId") String itemId, @RequestParam("quantity") int quantity) {
        try {
            cartService.updateQuantity(quantity, itemId, username);
            return Result.success("数量更新成功");
        } catch (Exception e) {
            return Result.failure("数量更新失败: " + e.getMessage());
        }
    }
}
